<template>
  <main>
    <div class="demo-collapse">
      <el-collapse accordion>
        <el-collapse-item v-for="item in list" :name="item.identity" @click="getInfo(item.identity)">
          <template #title>
            <div class="item">
              <div>{{ item.name }}</div>
              <div style="display: flex">
                <ConnectionManage @click.stop title="编辑" btn-type="text" :data="item"/>
                <el-popconfirm title="确认删除?" @confirm="connectionDelete(item.identity)">
                  <template #reference>
                    <el-button link type="danger" @click.stop>删除</el-button>
                  </template>
                </el-popconfirm>
              </div>
            </div>
          </template>
          <div id="dbs">
            <div v-for="db in infoDbList" @click="selectDb(item.identity,db.key)">
              <div v-if="db.key!==selectDbKey" class="my-item">{{ db.key }}({{ db.number }})</div>
              <div v-else class="my-select-item"> {{ db.key }}({{ db.number }})</div>
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
  </main>
</template>

<script setup>
import {ref, watch} from "vue";
import {ConnectionDelete, ConnectionList, DbList} from "../../wailsjs/go/main/App.js";
import {ElNotification} from "element-plus";
import ConnectionManage from "./ConnectionManage.vue";

let props = defineProps(['flush'])
watch(props, (nValue) => {
  connectionList()
})

let list = ref()
let infoDbList = ref()
let selectDbKey = ref()
let emits = defineEmits(['emit-select-db'])

//连接列表
function connectionList() {
  ConnectionList().then(res => {
    if (res.code !== 200) {
      ElNotification({
        title: res.msg,
        type: "error"
      })
      return
    }
    list.value = res.data
  })
}

//删除连接
function connectionDelete(id) {
  ConnectionDelete(id).then(res => {
    if (res.code !== 200) {
      ElNotification({
        title: res.msg,
        type: "error"
      })
      return
    }
    ElNotification({
      title: res.msg,
      type: "success"
    })
    connectionList()
  })

}

//获取基本信息
function getInfo(identity) {
  DbList(identity).then(res => {
    if (res.code !== 200) {
      ElNotification({
        title: res.msg,
        type: "error"
      })
      return
    }
    infoDbList.value = res.data
  })

}

//选中Db
function selectDb(connIdentity, dbKey) {
  selectDbKey.value = dbKey
  // db0
  emits('emit-select-db', connIdentity, Number(dbKey.substring(2)))
}

connectionList()
</script>

<style scoped>
#dbs {
  overflow: auto;
  max-height: 75vh;
}
</style>